<template>
	<div>
		<ProTable ref="proTable" title="门店管理" :columns="columns" :request-api="getTableList" :init-param="initParam">
			<template #searchHeader>
				<div class="mb16">
					<el-button type="primary" v-auth="'shop:management:sub:create:invoke'" @click="toUpdate()"> 新增门店 </el-button>
				</div>
			</template>
			<!-- 表格 功能 按钮 -->
			<template #otherButton>
				<el-button v-auth="'shop:management:sub:import:invoke'" @click="$router.push('/store/list/import')"> 导入 </el-button>
			</template>
			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>

			<!-- 表格操作 -->
			<template #operation="{ row }">
				<el-button type="primary" link v-auth="'shop:management:sub:switch:invoke'" @click="changeStatus(row)">
					{{ row.isopen ? '禁用' : '启用' }}
				</el-button>
				<el-divider direction="vertical" v-auth="'shop:management:sub:switch:invoke'" />
				<el-button type="primary" link v-auth-all="['shop:management:sub:details:invoke', 'shop:management:sub:edit:invoke']" @click="toUpdate(row)">
					编辑
				</el-button>
				<el-divider direction="vertical" v-auth-all="['shop:management:sub:details:invoke', 'shop:management:sub:edit:invoke']" />
				<el-button type="primary" link v-auth="'shop:management:sub:delete:invoke'" @click="onDelete(row)"> 删除 </el-button>
			</template>
		</ProTable>
	</div>
</template>

<script setup lang="tsx" name="storeList">
import { onMounted, ref, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { NextLoading } from '/@/utils/loading';
import ProTable from '../../../../components/ProTable/index.vue';
import { ProTableInstance, ColumnProps } from '../../../../components/ProTable/interface';
import { fetchStoreList, fetchDelStore, fetchStoreTypeList, fetchStoreStatus } from '/@/api/store';
import { useRouter } from 'vue-router';

const router = useRouter();
const storeTypes = ref([]);

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	paramCode: 'id',
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const getTableList = (params: any) => {
	let data = {
		...params,
	};
	if (data.paramValue) {
		data[data.paramCode] = data.paramValue;
	}
	delete data.paramValue;
	delete data.paramCode;

	return fetchStoreList(data);
};

// 表格配置项
const columns: ColumnProps<any>[] = [
	{
		prop: 'paramValue',
		label: '门店搜索',
		isShow: false,
		search: {
			span: 2,
			xs: 1,
			sm: 1,
			md: 2,
			lg: 1,
			xl: 1,
			render: (scope: any) => {
				const slot = {
					prepend: () => (
						<el-select
							v-model={scope.searchParam.paramCode}
							placeholder="Select"
							style="width: 100px"
							onChange={(value) => {
								scope.searchParam.paramCode = value;
							}}
						>
							{searchArr.map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
					),
				};
				return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={50}></el-input>;
			},
		},
	},
	{
		prop: 'id',
		label: '门店ID',
		minWidth: 100,
	},
	{
		prop: 'name',
		label: '门店名称',
		minWidth: 120,
	},
	{
		prop: 'code',
		label: '门店编码',
		minWidth: 100,
	},
	{
		prop: 'type',
		label: '门店类型',
		minWidth: 100,
		search: { el: 'select', props: { placeholder: '选择门店类型', clearable: true, filterable: true } },
		fieldNames: { label: 'name', value: 'id' },
		enum: () => {
			return new Promise<any>((resolve) => {
				fetchStoreTypeList({ page: 1, size: 99999 }).then((res: any) => {
					storeTypes.value = res.data.records;
					resolve({
						code: 200,
						msg: 'success',
						data: res.data.records,
					});
				});
			});
		},
		render: (scope: any) => {
			return storeTypes.value
				.filter((item: any) => scope.row.type.split(',').includes(item.id + ''))
				.map((item: any) => item.name)
				.join('、');
		},
	},
	{
		prop: 'isopen',
		label: '门店状态',
		minWidth: 100,
		search: { el: 'select', props: { placeholder: '请选择门店状态', clearable: true, filterable: true } },
		enum: [
			{
				label: '启用',
				value: true,
			},
			{
				label: '禁用',
				value: false,
			},
		],
	},
	{
		prop: 'locationDetail',
		minWidth: 200,
		label: '门店地址',
	},
	{
		prop: 'phone',
		minWidth: 140,
		label: '客服电话',
	},
	{
		prop: 'time',
		minWidth: 180,
		label: '营业时间',
	},

	{ prop: 'operation', label: '操作', fixed: 'right', width: 200, align: 'left' },
];

const searchArr = [
	{
		label: '门店ID',
		value: 'id',
	},
	{
		label: '门店名称',
		value: 'name',
	},
	{
		label: '门店编码',
		value: 'code',
	},
];

const getPlaceholder = computed(() => {
	const target = searchArr.find((item) => {
		return item.value == proTable.value?.searchParam.paramCode;
	});
	return target ? `输入${target?.label}搜索` : '';
});

const changeStatus = (row: any) => {
	const isOpen = row.isopen;
	ElMessageBox.confirm(`确认${isOpen ? '禁用' : '启用'}该门店?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		const res = await fetchStoreStatus({ id: row.id });
		if (res.code == 200) {
			ElMessage.success(isOpen ? '禁用成功' : '启用成功');
			proTable.value?.getTableList();
		}
	});
};

const toUpdate = (row?: any) => {
	router.push(row ? `/store/list/edit/${row.id}` : `/store/list/add`);
};

const onDelete = async (row: any) => {
	ElMessageBox.confirm('确认删除该门店?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		const res = await fetchDelStore({ id: row.id });
		if (res.code == 200) {
			ElMessage.success('删除成功');
			proTable.value?.getTableList();
		}
	});
};

// 页面加载时
onMounted(() => {
	NextLoading.done();
});
</script>

<style lang="scss">
.demo-tabs {
	.el-tabs__header {
		margin-bottom: 0;
	}
}
</style>
